<?php
namespace Model;


use Logger;
use Model\Factory\TableGatewayFactory;
use Zend\Db\ResultSet\ResultSet;


class User extends AbstractModel
{
    public $id;
    public $phone_number;
    public $username;
    public $name;
    public $password;
    public $created_date;
    public $created_by;
    public $active;
    public $is_log;
    public $email;
    public $deletable;

    /**
     * @return ResultSet
     */
    public function getAllRole()
    {

        $roleTable = TableGatewayFactory::getRoleTable();
        $select = $roleTable->getDbSqlSelect();
        $select->join(array('ur'=>'user_role'), 'ur.role_id = role.id', array())
            ->where(array('ur.person_id'=>$this->id));
//        Logger::debug($select->getSqlString($roleTable->getTableGateway()->getAdapter()->getPlatform()));
        $rsi = $roleTable->getTableGateway()->selectWith($select);
        $resultArr = array();
        foreach ($rsi as $aRole) {
            array_push($resultArr, $aRole);
        }

        return $resultArr;
    }

    public function detachAllRole(){
        $roleSet = $this->getAllRole();
        foreach ($roleSet as $userRole) {
            $userRoleTable = new UserRoleTable();
            $userRoleTable->delete($userRole->id);
        }
    }

    public function addRole($roleId)
    {
        if($this->isHavingRole($roleId))
            return;

        $userRoleTable = TableGatewayFactory::getUserRoleTable();
        $userRoleTable->insert(array("person_id"=>$this->id,"role_id"=>$roleId));
    }

    public function isHavingRole($roleId)
    {
        $allRoles = $this->getAllRole();
        $result = false;
        foreach ($allRoles as $roleItem) {
            if($roleItem->id == $roleId) $result = true;
        }
        return $result;
    }

    public function isHavingPrivilege($privilege)
    {
        $allRole = $this->getAllRole();
        foreach ($allRole as $roleItem) {
            if($roleItem->isHavingPrivilege($privilege))
                return true;
        }

        return false;
    }

    public function getActiveDomains(){
        $domainTable = TableGatewayFactory::getRestaurantTable();
        return $domainTable->getDomainOfUser($this->id);
    }

    public function isHavingDomain($domainCode)
    {
        $allDomain = $this->getActiveDomains();
        $isHavingDomain = false;
        foreach ($allDomain as $domainItem) {
            if(strtolower($domainItem->domain) == strtolower($domainCode))
                $isHavingDomain = true;
        }
        return $isHavingDomain;
    }
}
